import React from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {connectActionSheet} from '@expo/react-native-action-sheet';
import ListItem from '../../components/list-item';
import {FlatList, Platform, StyleSheet, Text, View} from 'react-native';
import {getRealSize, Touchable} from '../../utils';
import ThemeStyles from '../../styles';
import _ from 'lodash';
import MessageItem from './message-item';
import Separator from '../../components/separator';
import {LoadingStatus} from '../../reducers/app-state';
import {I18n} from '../../reducers/intl';
import * as messageActionCreator from '../../actions/message-actions';
import * as orderActionCreator from '../../actions/order-actions';
import {UserType} from '../../reducers/user';

class MessagesScreen extends React.Component {
  static navigationOptions = ({navigation}) => ({
    headerBackTitleStyle: Platform.OS === 'ios' && {
      height: 0,
      width: 0,
    },
    title: I18n.t('page.title.chat'),
    headerRight: () => (
      <Touchable onPress={() => navigation.goBack()}>
        <View
          style={[ThemeStyles.Layout.base.padding, {height: getRealSize(48)}]}>
          <Text style={[ThemeStyles.Front.base]}>{I18n.t('button.read')}</Text>
        </View>
      </Touchable>
    ),
  });

  componentDidMount() {
    const {messageActions} = this.props;
    messageActions.loadMessages();
    // navigation.addListener('willFocus', () => messageActions.loadMessages());
  }

  toOrder = item => {
    const {navigation, orderActions} = this.props;
    navigation.navigate('OrderMessagesTab', {item});
    orderActions.loadOrder(item.id);
  };

  render() {
    const {
      orderMessages = {},
      navigation,
      appState,
      messageActions,
      user,
    } = this.props;
    const messages = Object.values(orderMessages);
    const unreadSysMsgCount = appState.unreadSysMsg
      ? `${appState.unreadSysMsg.length}`
      : ' ';
    // console.log('unreadSysMsgCount', unreadSysMsgCount);
    return (
      <FlatList
        data={_.orderBy(messages, 'created', 'desc')}
        refreshing={appState.loading === LoadingStatus.PENDING}
        onRefresh={() => messageActions.loadMessages()}
        keyExtractor={item => item.id}
        ItemSeparatorComponent={() => <Separator />}
        ListHeaderComponent={() => (
          <ListItem
            label={I18n.t('menu.sysmessage')}
            extra={unreadSysMsgCount}
            arrow={true}
            onPress={() => navigation.navigate('Notice')}
          />
        )}
        renderItem={({item}) => (
          <MessageItem
            {...item}
            unread={
              [UserType.dentist, UserType.clinic].includes(user.type)
                ? item.unread
                : item.vendor_unread
            }
            onChat={() => navigation.navigate('Chat', {item})}
            toOrder={() => this.toOrder(item)}
          />
        )}
      />
    );
  }
}

const mapStateToProps = state => ({
  appState: state.appState,
  user: state.user,
  orderMessages: state.orderMessageList,
  systemMessages: state.systemMessageList,
});

const mapDispatchToProps = dispatch => ({
  messageActions: bindActionCreators(messageActionCreator, dispatch),
  orderActions: bindActionCreators(orderActionCreator, dispatch),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(connectActionSheet(MessagesScreen));

const Styles = StyleSheet.create({
  container: {
    ...ThemeStyles.Color.background.white,
  },
});
